/**
 * 计算iframe高度
 * @author Abel
 * @param  {element} _iframe 需要计算的iframe节点
 * @param  {element} _html   iframe下的html节点
 * @return {undefine}        默认返回值
 */
function resizeIframe(_iframe,_html) {
    window.onresize = function() {
        _iframe.style.cssText += 'height:' + window.getComputedStyle(_html, null).height;
    };
    setTimeout("window.onresize();",500);   // 为了兼容火狐
};

/**
 * 预加载几个独立的的组件(element/form/table/laydate/tree不能复用！)
 * @author Abel
 * @return {undefine} 默认返回值
 */
(function module() {
    var _this = this;
    layui.use(['jquery','layer'], function() { _this.mod = layui; });
})(this);

/**
 * 判断element节点是否包含class值
 * @author Abel
 * @param  {element}    elements    节点
 * @param  {String}     cName       class名称
 * @return {Boolean}    true|false  包含|不包含
 */
function hasClass(elements,cName){ 
    return !!elements.className.match(new RegExp("(\\s|^)" + cName + "(\\s|$)") );
};

/**
 * 为element节点添加class值
 * @author Abel
 * @param  {element}    elements    节点
 * @param  {String}     cName       class名称
 * @return {undefine}               默认返回值
 */
function addClass(elements,cName){ 
    if(!hasClass(elements,cName)){ 
        elements.className += " " + cName; 
    }; 
}; 

/**
 * 为element节点删除class值
 * @author Abel
 * @param  {element}    elements    节点
 * @param  {String}     cName       class名称
 * @return {undefine}               默认返回值
 */
function removeClass(elements,cName){ 
    if(hasClass(elements,cName)){ 
        elements.className = elements.className.replace(new RegExp("(\\s|^)" + cName + "(\\s|$)" ),"" );
    }; 
};

function config_dom() {
    var domFun = new _dom();
    domFun.setData("layui-body", document.querySelector(".layui-body"));    // 滚动主体
    domFun.setData("layui-tab-title", document.querySelector(".layui-tab-title"));  // 横向Tab的父元素
    domFun.setData("layui-nav-tree", document.querySelector(".layui-nav-tree"));  // 左侧导航列表祖先元素
};

// 创建私有属性和方法
;(function(){
    // 表格滚动相关
    var scrollData = Object.create(null);
    _scroll = function(){};
    _scroll.prototype.getData = function(key) {
        if (key) return scrollData[key];
        return scrollData;
    };
    _scroll.prototype.setData = function(index, arr) {
        scrollData[index] = arr;
    };
    _scroll.prototype.clearData = function() {
        for ( var key in scrollData ) {
            delete scrollData[key];
        }
    };

    // 页面DOM元素相关
    var domData = Object.create(null);
    _dom = function(){};
    _dom.prototype.getData = function(key) {
        if (key) return domData[key];
        return domData;
    };
    _dom.prototype.setData = function(key, value) {
        domData[key] = value;
    };
    config_dom();

    // 登录用户信息
    var userData = Object.create(null);
    _user = function(){};
    _user.prototype.getData = function(key) {
        if (key) return userData[key];
        return userData;
    };
    _user.prototype.setData = function(key, value) {
        userData[key] = value;
    };
    _user.prototype.clearData = function() {
        for ( var key in userData ) {
            delete userData[key];
        }
    }

    // 左侧菜单信息
    var leftMenuData = Object.create(null);
    _leftMenu = function(){};
    _leftMenu.prototype.getData = function(key) {
        if (key) return userData[key];
        return leftMenuData;
    };
    _leftMenu.prototype.setData = function(key, value) {
        leftMenuData[key] = value;
    };
    _leftMenu.prototype.clearData = function() {
        for ( var key in leftMenuData ) {
            delete leftMenuData[key];
        }
    }

    //TODO template 模版定义
    var tplData = Object.create(null);
    _tpl = function(){};
    _tpl.prototype.getData = function(key) {
        if (key) return tplData[key];
        return tplData;
    };
    _tpl.prototype.setData = function(Obj) {    // 参数为 对象形式
        for ( key in Obj )
        tplData[key] = Obj[key];
    }

})();

/**
 * 禁止表头拉伸
 * @param  {jQuery} $dom    当前iframe内的某个元素
 * @return {undefine}       默认返回值
 */
function stopDrag($dom) {
    $dom.parents('body').find('th').on('mousemove', function() {
        return false;
    }).css('cursor', 'default');
};
/**
 * 表格水平位移
 * @param  {jQuery}     $                 jQuery对象
 * @param  {element}    $table            表格主体
 * @param  {element}    $tableHeaderClone 悬浮的表头
 * @return {undefine}                     默认返回值
 */
function transverseDrag($, $table, $tableHeaderClone) {
    var visualWidth = $table.width();               // table可视区宽度
    var reallyWidth = $tableHeaderClone.width();    // table实际宽度
    var scrollWidth = reallyWidth - visualWidth;    // 可滑动距离
    var prevMoveX;  // 前一次移动横坐标
    var moveX;      // 移动横坐标
    var elem    = $table[0];            // table滚动实体

    $table.on('mousedown mousemove mouseup', function(e){
        if ( 'mousedown' === e.type ) {
            this.flag = true;
            prevMoveX = e.pageX;
        } else if ( 'mousemove' === e.type && this.flag ) {
            moveX = e.pageX;
            var offset = elem.scrollLeft+moveX-(prevMoveX?prevMoveX:moveX);
            if ( offset <= 0 ) {
                offset = 0;
            } else if ( offset >= scrollWidth ) {
                offset = scrollWidth;
            }
            elem.scrollTo(offset, 0);
            $tableHeaderClone.css('left', -offset+"px");
            prevMoveX = moveX;
        } else if ( 'mouseup' === e.type ) {
            this.flag = false;
        }
    });
};
/**
 * table表头悬浮置顶
 * @param  {jQuery}     $       jQuery对象
 * @param  {element}    $table  表头所在的表格元素
 * @param  {Number}     index   当前页table的索引值
 * @param  {Boolean}    isClear 是否清空之前的数据
 * @return {undefine}           默认返回值
 */
function tableHeaderFixed($, $table, index, isClear) {
    var $tableHeader = $table.next('.layui-table-view');
    var $dom = $($.clone($tableHeader[0], true));

    var scrollFun = new _scroll();
    isClear ? scrollFun.clearData() : 0;

    stopDrag($table);
    $dom.find('.layui-table-box>*:not(:first-child)').remove();
    $dom.find('.layui-table-page').remove();
    /*
     * param1: 当前页table的索引值
     * param2: 表格的高度
     * param3: 表格距离顶部的距离
     * param4: 克隆的表头节点
     */
    scrollFun.setData(index, [$tableHeader.find('.layui-table-box').height(), $tableHeader.offset().top, $dom])
    scrollData = scrollFun.getData(); // 设立全局变量scrollData
    tableScroll($, $table);

    if ( $tableHeader.find('.layui-table').width() > $tableHeader.width() ) {
        setTimeout(function(){
            transverseDrag($, $tableHeader.find('.layui-table-body.layui-table-main'), $dom);    // 启动横向平移函数
        }, 500);
    }
};
/**
 * 表头浮现规则
 * @return {[type]}       [description]
 */
function tableScroll($, $table) {
    var domFun = new _dom();
    var layuiBody = domFun.getData('layui-body');
    var cssStyleObj = Object.create(null);
    for ( var i = 0, len = Object.getOwnPropertyNames(scrollData).length; i < len; i++ ) {
        $table.parents('body').children('.custom-scrollPosition[lay-filter='+$(scrollData[i][2]).attr('lay-filter')+']').remove();
        $table.parents('body').append($(scrollData[i][2]).addClass('custom-scrollPosition custom-hide'));
    }
    $(layuiBody).on('scroll', function(){
        if ( !Object.getOwnPropertyNames(scrollData).length ) return;
        
        var translateY = $(this).scrollTop()-51;
        cssStyleObj = {
            // 'top': $(this).scrollTop()-51+'\\9',
            'transform': 'translateY('+translateY+'px)',
            '-ms-transform': 'translateY('+translateY+'px)',
            '-moz-transform': 'translateY('+translateY+'px)',
            '-webkit-transform': 'translateY('+translateY+'px)',
            '-o-transform': 'translateY('+translateY+'px)'
        };
        if ( $(this).scrollTop() > 60 && $(this).scrollTop() < scrollData[0][0] ) {
            if (scrollData[0]) $(scrollData[0][2]).removeClass('custom-hide').css(cssStyleObj);
        } else {
            if ( scrollData[0] ) $(scrollData[0][2]).addClass('custom-hide').css(cssStyleObj);
            if ( scrollData[1] && $(this).scrollTop() > scrollData[1][1]+60 && $(this).scrollTop() < scrollData[1][1]+scrollData[1][0]-40 ) {
                $(scrollData[1][2]).removeClass('custom-hide').css(cssStyleObj);
            } else {
                if (scrollData[1]) $(scrollData[1][2]).addClass('custom-hide').css(cssStyleObj);
            }
        }
    });
};

// 初始化绑定事件
function bindEvents() {
    var domFun = new _dom();
    domFun.getData('layui-tab-title').addEventListener('click', function(e){ // IE8+
        var target = e.srcElement ? e.srcElement : e.target;
        var id = 0;
        var aimId = id;
        if ( 'li' === target.tagName.toLocaleLowerCase() ) {    // 切换
            id = +(target.getAttribute('lay-id') || id);
            if ( id ) domFun.getData('layui-nav-tree').querySelector('a[data-id=\"'+id+'\"]').click();
            else { removeClass(domFun.getData('layui-nav-tree').querySelector('.layui-this'), 'layui-this') };
        } else if ( 'i' === target.tagName.toLocaleLowerCase() ) {  // 删除
            aimId = domFun.getData('layui-tab-title').querySelector('.layui-this').getAttribute('lay-id');
            if ( aimId ) domFun.getData('layui-nav-tree').querySelector('a[data-id=\"'+aimId+'\"]').click();
            else removeClass(domFun.getData('layui-nav-tree').querySelector('.layui-this'), 'layui-this');
        }
    }, false);
};
bindEvents();

// 对象数组根据对象内某一属性值进行排序
function compareArrObj(property, type){
    return function(obj1,obj2){
        if ( 'asc' === type ) return obj1[property]>obj2[property];     // 升序
        return obj2[property]<obj1[property];     // 默认降序
    }
}

// 取两个数组的差值
function diffArr(arr1, arr2) {
    arr1 = arr1.filter(function(x) { return x !== undefined && x != null; });
    arr2 = arr2.filter(function(x) { return x !== undefined && x != null; });
    var hash = {}, i = 0, len = 0, step;
    for ( i, len = arr2.length; i < len; i++ ) {
        step = arr2[i];
        hash[step.id] = step;
    }
    for ( i = 0, len = arr1.length; i < len; i++ ) {
        if (arr1[i].id in hash) delete arr1[i];
    }
    return arr1.filter(function(x) { return x !== undefined && x != null; });
}

// 列表新增 弹出页面
function layerOpenParams($, layer, params, id, callback, form, setSelectWidth) {
    layer.open({
        title: '新增',
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        btn: ['确定', '重置', '取消'],
        area: ['60%', '60%'], //宽高
        content: factoryOfInputDom($, params, id),
        yes: function(index) {
            callback(id, index, $);
        },
        btn2: function(index) {
            layer.close(index);
            setTimeout(function(){
                layerOpenParams($, layer, params, id, callback, form, setSelectWidth);
                form.render();
                setSelectWidth();
            }, 0);    // layer.close() 销毁元素会有200ms的延迟 (经修改后改为了0ms)
        },
        btn3: function() {
            console.log('关闭');
        }
    });
}

// 表单元素 工厂
function factoryOfInputDom($, params, id) {
    var cdf = document.createDocumentFragment();
    cdf = "<div class='layui-form' id="+id+"><div class='layui-form-item'>";
    for ( var i = 0, len = params.length; i < len; i++ ) {
        var type = params[i].type.indexOf('-') >=0 ? params[i].type.split('-')[1] : params[i].type;
        switch (type) {
            case 'text':
                if ( params[i].display ) {
                    cdf += '<div class="custom-whole-'+ params[i].display +'">' + getInputOfType(params[i], type) + '</div>';
                } else {
                    cdf += '<div class="custom-whole-block">' + getInputOfType(params[i], type) + '</div>';
                }
                break;
            case 'textarea':
                if ( params[i].display ) {
                    cdf += '<div class="custom-whole-'+ params[i].display +'">' + getTexteare(params[i], type) + '</div>';
                } else {
                    cdf += '<div class="custom-whole-block">' + getTexteare(params[i], type) + '</div>';
                }
                break;
            case 'select':
                if ( params[i].display ) {
                    cdf += '<div class="custom-whole-'+ params[i].display +'">' + getSelect(params[i], type) + '</div>';
                } else {
                    cdf += '<div class="custom-whole-block">' + getSelect(params[i], type) + '</div>';
                }
                break;
            default:
                break;
        }
    }
    cdf += "</div></div>";
    return cdf;
}
// input
function getInputOfType(param, type) {
    var cdf = document.createDocumentFragment();
    cdf = [
        '<label class="layui-form-label custom-fs16">'+param.title+'</label>'
        ,'<div class="layui-input-'+param.display+'">'
        ,'<input style="width:'+param.width+'" {pla1} id='+param.id+' type="'+type+'" value="'+param.value+'" lay-verify='+param.verify+' placeholder="'+param.placeholder+'" autocomplete="off" class="layui-input custom-fs16 {pla2}" />'
        ,'</div>'
    ].join('');
    if ( param.readonly ) {
        cdf = cdf.replace('{pla1}', 'readonly').replace('{pla2}', 'custom-readonly');
    } else {
        cdf = cdf.replace('{pla1}', '').replace('{pla2}', '');
    }
    return cdf;
}
// texteare
function getTexteare(param) {
    var cdf = document.createDocumentFragment();
    cdf = [
        '<label class="layui-form-label custom-fs16">'+param.title+'</label>'
        ,'<div class="layui-input-'+param.display+'">'
        ,'<textarea style="width:'+param.width+'" {pla1} id='+param.id+' placeholder="'+param.placeholder+'" class="layui-textarea custom-fs16 {pla2}" rows="5">'+param.value+'</textarea>'
        ,'</div>'
    ].join('');
    if ( param.readonly ) {
        cdf = cdf.replace('{pla1}', 'readonly').replace('{pla2}', 'custom-readonly');
    } else {
        cdf = cdf.replace('{pla1}', '').replace('{pla2}', '');
    }
    return cdf;
}
// select
function getSelect(param) {
    var cdf = document.createDocumentFragment();
    if ( param.options.length ) {   // 有固定选项值则不发送请求
        var arr = [
            '<label class="layui-form-label custom-fs16">'+param.title+'</label>'
            ,'<div class="layui-input-'+param.display+' custom-fs16">'
            ,'<select lay-verify="'+param.verify+'" id='+param.id+'>'
        ]
        if ( param.placeholder ) arr[arr.length] = '<option value="">'+param.placeholder+'</option>';
        for ( var i = 0, len = param.options.length; i < len; i++ ) {
            var value;
            if ( param.rule ) {
                value = param.rule[param.options[i]] ? param.rule[param.options[i]] : param.options[i];
            }
            if ( param.value === param.options[i] ) {
                arr[arr.length] = '<option selected value="'+( param.rule?param.options[i]:i+1)+'">'+ (value || param.options[i]) +'</option>'
            } else {
                arr[arr.length] = '<option value="'+( param.rule?param.options[i]:i+1)+'">'+ (value || param.options[i]) +'</option>'
            }
        }
        arr[arr.length] = '</select></div>';
        cdf = arr.join('');
        return cdf;
    } else {    // 为级联做准备  单个的推荐用上面的方法
        $.ajax({
            url: param.url,
            type: 'get',
            dataType: 'json',
            data: param.data,
        })
        .done(function() {
            console.log("success");
        })
        .fail(function() {
            console.log("error");
        })
        .always(function() {
            console.log("complete");
        });
    }

} 